using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;

namespace DotConferenceSql
{
    /// <summary>
    /// Genertic UPDATE clause element
    /// </summary>
    public class UpdateQueryElement : QueryElementBase
    {
        private List<QueryFieldValue> Fields = new List<QueryFieldValue>();

        private string m_table;
        /// <summary>
        /// Gets or sets the table.
        /// </summary>
        /// <value>The table.</value>
        public string Table
        {
            get
            {
                return m_table;
            }
            set
            {
                m_table = value;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="UpdateQueryElement"/> class.
        /// </summary>
        public UpdateQueryElement()
            : base()
        {
            Type = QueryElementType.UpdateClause;
        }

        /// <summary>
        /// Adds the field with the specified value
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="value">The value.</param>
        public void Add(string field, object value)
        {
            QueryFieldValue newField = new QueryFieldValue();
            newField.field = field;
            newField.value = value;

            Fields.Add(newField);

            // Add SQL parameter too
            Parameters.Add(new SqlParameter(newField.ParamId, value));
        }

        /// <summary>
        /// Generate the part of the query for this element.
        /// </summary>
        /// <returns>generated SQL fragment</returns>
        public override string BuildTextQuery()
        {
            if (String.IsNullOrEmpty(Table))
            {
                throw new ArgumentException("Table argument not specified");
            }

            if (Fields.Count == 0)
            {
                throw new ArgumentException("This query element does not contain any field");
            }

            // UPDATE <table> SET field = value, field = value
            StringBuilder query = new StringBuilder();
            query.Append(Table);
            
            query.Append(" SET ");
            List<string> updateStatements = new List<string>();
            foreach (QueryFieldValue field in Fields)
            {
                updateStatements.Add(String.Format("{0} = {1}", field.field, field.ParamId));
            }

            query.Append(String.Join(",", updateStatements.ToArray()));

            return query.ToString();
        }
    }
}